package com.css.msgcenter.server;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.css.apps.task.job.JobTemplate;
import com.css.db.query.TransactionCache;
import com.css.msgcenter.Results;
import com.css.msgcenter.server.model.MsgMain;
import com.css.msgcenter.server.model.MsgTask;
import com.css.msgcenter.server.model.MsgTaskLog;
import com.css.util.UuidUtil;

public class MessageJob extends JobTemplate {
	private static BizLog log = new BizLog(MessageJob.class);
	
	public List beforeJob() {
		log.info("MsgJob beforeJob---"+Calendar.getInstance().getTime());
		TransactionCache tx = null;
		try{
//			等待执行的任务，一直在队列中但过180分钟无回应的任务
			List<MsgTask> taskList = new QueryMsg("select * from msg_task a where a.msg_status=:wait or " 
				+"(a.msg_status=:sending and a.begin_time<(sysdate - interval '"+Constants.MAX_TIME+"' hour))", true)
				.setParameter("wait", Constants.STASUS_WAITING)
				.setParameter("sending", Constants.STASUS_SENDING)
				.addEntity("a", MsgTask.class)
				.list();
			
//			把任务状态改为队列中
			if(taskList != null && taskList.size() > 0) {
				Date cur = (Date) new QueryMsg("select sysdate from dual", true).uniqueResult();
				for(MsgTask t : taskList) {
					t.setMsgStatus(Constants.STASUS_SENDING);
					t.setBeginTime(cur);
				}
				tx = new QueryMsg().getTransaction();
				tx.update(taskList);
			}
			return taskList;
		} catch(Exception ex){
			if (tx != null) {
				tx.rollback();
			}
			log.error(ex.getMessage(), ex);
			return null;
		}
		
	}
	public void doJob(Object obj) {
		log.info("MsgJob doJob---"+Calendar.getInstance().getTime());
		TransactionCache tx = null;
		try{
			MsgTask tt = (MsgTask) obj;
			MsgMain mm = QueryMsg.get(MsgMain.class, tt.getMsgId());
			
//			任务如果在队列中150分钟未执行，则返回，等每180分钟重新执行一次,。
//			GregorianCalendar calTmp = new GregorianCalendar();
//			calTmp.add(GregorianCalendar.MINUTE, -150);
//			Date former = calTmp.getTime();
//			if(tt.getBeginTime().getTime()-former.getTime() < 0)
//				return;
				
//			发送
//			Date begin = (Date) new QueryMsg("select sysdate from dual", true).uniqueResult();
			MessageResult pRes = PushFactory.create(tt.getMsgType()).send(tt, mm);
			Date end = (Date) new QueryMsg("select sysdate from dual", true).uniqueResult();
			
//			发送结果处理
			String status;
			switch(pRes.getResult()) {
			case Results.SUCCESS:
				status = Constants.STASUS_SUCCESS;
				break;
			default:
				status = Constants.STASUS_FAILED;
			}

//			记日志
			List lsta = new ArrayList();
			List lstb = new ArrayList();
			MsgTaskLog tl = new MsgTaskLog();
			tl.setUuid(UuidUtil.getUuid());
			tl.setTaskId(tt.getUuid());
			tl.setSender(mm.getSender());
			tl.setMsgType(tt.getMsgType());
			tl.setReceiver(tt.getReceiverName());
			tl.setServerIp(java.net.InetAddress.getLocalHost().getHostAddress());
			tl.setMsgStatus(status);
			tl.setMsgStatusInfo(pRes.toStringInfo());
			tl.setCreateTime(end);
			lsta.add(tl);

			
//			若任务未完成 ，更新task
			if(status.equals(Constants.STASUS_FAILED)
					&&tt.getFailCount()+1 < Constants.TRY_COUNT) {
				tt.setFailCount(tt.getFailCount()+1);
				tt.setMsgStatus(Constants.STASUS_WAITING);
				lstb.add(tt);
			
				
//			若任务已完成，更新task，更新main
			} else {
				if(status.equals(Constants.STASUS_FAILED))
					tt.setFailCount(tt.getFailCount()+1);
				tt.setFinishTime(end);
				tt.setMsgStatus(status);
				lstb.add(tt);
				
				if(status.equals(Constants.STASUS_SUCCESS)) {
					mm.setTaskSuccess(mm.getTaskSuccess()+1);
				} else if(status.equals(Constants.STASUS_INVALID)) {
					mm.setTaskInvalid(mm.getTaskInvalid()+1);
				} else if(status.equals(Constants.STASUS_FAILED)) {
					mm.setTaskFail(mm.getTaskFail()+1);
				}
				if(mm.getTaskSuccess() + mm.getTaskFail() + mm.getTaskInvalid()
						>= mm.getTaskSum()) {
					mm.setLastExecTime(end);
					mm.setMsgStatus(Constants.STASUS_SUCCESS);
				}
				lstb.add(mm);
			}
			tx = new QueryMsg().getTransaction();
			tx.save(lsta);
			tx.update(lstb);
			tx.commit();
			
		} catch(Exception ex){
			if (tx != null) {
				tx.rollback();
			}
			log.error(ex.getMessage(), ex);
		}
		
		
		
		
		
	}
}
